﻿using System;
using System.Data;
using System.Text;
using System.Reflection;
using System.Collections.Generic;
using System.Data.SqlClient;
using ByteSite.DBUtility;
using ByteSite.Common;
using SqlSugar;
using System.Dynamic;
using System.Linq.Expressions;
using System.Linq;

namespace ByteSite.DAL
{
	/// <summary>
	/// 数据访问类:文章内容
	/// </summary>
	public partial class article
    {
        public SqlSugarClient db;
        private string databaseprefix; //数据库表名前缀
        public article(string _databaseprefix)
        {
            databaseprefix = _databaseprefix;
            db = new DBUtility.DbContext().Db;
        }
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string channelName, int article_id)
        {
            object obj = db.Queryable<Entitys.article>().AS(databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName).Where(x => x.id == article_id).First();
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string channelName, string call_index)
        {
            object obj = db.Queryable<Entitys.article>().AS(databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName).Where(x => x.call_index == call_index).First();
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

		/// <summary>
		/// 增加一条数据
		/// </summary>
        public int Add(Entitys.article model)
        {
            //查询频道名称
            string channelName = db.Queryable<Entitys.dt_site_channel>().Where(x => x.id == model.channel_id).First().name;
            if (channelName.Length == 0)
            {
                return 0;
            }
            try
            {
                db.BeginTran();

                #region 修改主表数据====================
                string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
                model.id = db.Insertable(model).AS(table).ExecuteReturnIdentity();

                //扩展字段信息
                if (model.fields != null)
                {
                    if (model.fields.Count > 0)
                    {
                        model.fields.Add("id", model.id);
                        db.Updateable(model.fields).AS(table).WhereColumns("id").ExecuteCommand();
                    }
                }
                #endregion

                #region 添加图片相册====================
                if (model.albums != null)
                {
                    if (model.albums.Count > 0)
                    {
                        int i = 1;
                        DateTime now = DateTime.Now;
                        foreach (Entitys.dt_article_albums album in model.albums)
                        {
                            album.channel_id = model.channel_id;
                            album.article_id = model.id;
                            album.add_time = now;
                            album.sort_id = i;
                            i++;
                            if (album.id > 0)
                            {
                                new DAL.Data().Update(album);
                            }
                            else
                            {
                                new DAL.Data().Insert(album);
                            }
                        }
                    }
                }
                #endregion

                #region 添加内容附件====================
                if (model.attach != null)
                {
                    if (model.attach.Count > 0)
                    {
                        int i = 1;
                        DateTime now = DateTime.Now;
                        foreach (Entitys.dt_article_attach attach in model.attach)
                        {
                            attach.channel_id = model.channel_id;
                            attach.article_id = model.id;
                            attach.add_time = now;
                            attach.sort_id = i;
                            i++;

                            if (attach.id > 0)
                            {
                                new DAL.Data().Update(attach);
                            }
                            else
                            {
                                new DAL.Data().Insert(attach);
                            }
                        }
                    }
                }
                #endregion

                #region 添加商品价格====================
                if (model.goods != null)
                {
                    if (model.goods.Count > 0)
                    {
                        foreach (Entitys.dt_article_goods goods in model.goods)
                        {
                            goods.channel_id = model.channel_id;
                            goods.article_id = model.id;
                        }
                        new DAL.Data().Insert(model.goods);
                    }
                }
                #endregion

                #region 添加商品规格====================
                if (model.specs != null)
                {
                    if (model.specs.Count > 0)
                    {
                        foreach (Entitys.dt_article_goods_spec specs in model.specs)
                        {
                            specs.channel_id = model.channel_id;
                            specs.article_id = model.id;
                        }
                        new DAL.Data().Insert(model.specs);
                    }
                }
                #endregion

                #region 添加Tags标签====================
                if (model.tags != null && model.tags.Trim().Length > 0)
                {
                    string[] tagsArr = model.tags.Trim().Split(',');
                    if (tagsArr.Length > 0)
                    {
                        List<Entitys.dt_article_tags> tags = new List<Entitys.dt_article_tags>();
                        foreach (string tag in tagsArr)
                        {
                            Entitys.dt_article_tags tagModel = new DAL.Data().Get<Entitys.dt_article_tags>(x => x.title == tag);
                            if (tagModel == null)
                            {
                                tagModel = new Entitys.dt_article_tags();
                                tagModel.title = tag;
                                tagModel.sort_id = 99;
                                tagModel.is_red = 0;
                                tagModel.add_time = DateTime.Now;
                                new DAL.Data().Insert(tagModel);
                            }
                        }
                    }
                }
                #endregion

                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                return 0;
            }
            return model.id;
        }

		/// <summary>
		/// 更新一条数据
		/// </summary>
		public bool Update(Entitys.article model)
		{
            //查询频道名称
            string channelName = db.Queryable<Entitys.dt_site_channel>().Where(x => x.id == model.channel_id).First().name;
            if (channelName.Length == 0)
            {
                return false;
            }

            try
            {

                db.BeginTran();

                #region 修改主表数据====================
                string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
                db.Updateable(model).AS(table).ExecuteCommand();

                //扩展字段信息
                if (model.fields != null)
                {
                    if (model.fields.Count > 0)
                    {
                        model.fields.Add("id", model.id);
                        db.Updateable(model.fields).AS(table).WhereColumns("id").ExecuteCommand();
                    }
                }
                #endregion

                #region 修改图片相册====================
                if (model.albums != null)
                {
                    if (model.albums.Count > 0)
                    {
                        int i = 1;
                        DateTime now = DateTime.Now;
                        foreach (Entitys.dt_article_albums album in model.albums)
                        {
                            album.channel_id = model.channel_id;
                            album.article_id = model.id;
                            album.add_time = now;
                            album.sort_id = i;
                            i++;

                            if (album.id > 0)
                            {
                                new DAL.Data().Update(album);
                            }
                            else
                            {
                                new DAL.Data().Insert(album);
                            }
                        }
                        //new DAL.Data().Update(model.albums);
                    }
                    else {
                        new DAL.Data().Delete<Entitys.dt_article_albums>(x => x.channel_id == model.channel_id && x.article_id == model.id);
                    }
                }
                #endregion

                #region 修改内容附件====================
                if (model.attach != null)
                {
                    if (model.attach.Count > 0)
                    {
                        int i = 1;
                        DateTime now = DateTime.Now;
                        foreach (Entitys.dt_article_attach attach in model.attach)
                        {
                            attach.channel_id = model.channel_id;
                            attach.article_id = model.id;
                            attach.add_time = now;
                            attach.sort_id = i;
                            i++;

                            if (attach.id > 0)
                            {
                                new DAL.Data().Update(attach);
                            }
                            else
                            {
                                new DAL.Data().Insert(attach);
                            }

                        }
                        //new DAL.Data().Update(model.attach);
                    }
                    else
                    {
                        new DAL.Data().Delete<Entitys.dt_article_attach>(x => x.channel_id == model.channel_id && x.article_id == model.id);
                    }
                }
                #endregion

                #region 修改商品价格====================
                new DAL.Data().Delete<Entitys.dt_article_goods>(x => x.channel_id == model.channel_id && x.article_id == model.id);
                if (model.goods != null)
                {
                    if (model.goods.Count > 0)
                    {
                        foreach (Entitys.dt_article_goods goods in model.goods)
                        {
                            goods.channel_id = model.channel_id;
                            goods.article_id = model.id;
                        }
                        new DAL.Data().Insert(model.goods);
                    }
                }
                #endregion

                #region 修改商品规格====================
                new DAL.Data().Delete<Entitys.dt_article_goods_spec>(x => x.channel_id == model.channel_id && x.article_id == model.id);
                if (model.specs != null)
                {
                    if (model.specs.Count > 0)
                    {
                        foreach (Entitys.dt_article_goods_spec specs in model.specs)
                        {
                            specs.channel_id = model.channel_id;
                            specs.article_id = model.id;
                        }
                        new DAL.Data().Insert(model.specs);
                    }
                }
                #endregion

                #region 添加Tags标签====================
                if (model.tags != null && model.tags.Trim().Length > 0)
                {
                    string[] tagsArr = model.tags.Trim().Split(',');
                    if (tagsArr.Length > 0)
                    {
                        List<Entitys.dt_article_tags> tags = new List<Entitys.dt_article_tags>();
                        foreach (string tag in tagsArr)
                        {
                            Entitys.dt_article_tags tagModel = new DAL.Data().Get<Entitys.dt_article_tags>(x => x.title == tag);
                            if (tagModel == null)
                            {
                                tagModel = new Entitys.dt_article_tags();
                                tagModel.title = tag;
                                tagModel.sort_id = 99;
                                tagModel.is_red = 0;
                                tagModel.add_time = DateTime.Now;
                                new DAL.Data().Insert(tagModel);
                            }
                        }
                    }
                }
                #endregion

                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                return false;
            }
            return true;
		}

		/// <summary>
		/// 删除一条数据
		/// </summary>
		public bool Delete(string channelName, int channelId, int articleId)
        {
            try
            {
                db.BeginTran();

                string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;

                db.Deleteable<Entitys.dt_article_albums>(x => x.channel_id == channelId && x.article_id == articleId).ExecuteCommand();
                db.Deleteable<Entitys.dt_article_attach>(x => x.channel_id == channelId && x.article_id == articleId).ExecuteCommand();
                db.Deleteable<Entitys.dt_user_group_price>(x => x.channel_id == channelId && x.article_id == articleId).ExecuteCommand();
                db.Deleteable<Entitys.dt_article_goods>(x => x.channel_id == channelId && x.article_id == articleId).ExecuteCommand();
                db.Deleteable<Entitys.dt_article_goods_spec>(x => x.channel_id == channelId && x.article_id == articleId).ExecuteCommand();
                db.Deleteable<Entitys.dt_article_tags_relation>(x => x.channel_id == channelId && x.article_id == articleId).ExecuteCommand();
                db.Deleteable<Entitys.dt_article_comment>(x => x.channel_id == channelId && x.article_id == articleId).ExecuteCommand();
                //model.id = db.Insertable(model).AS(table).ExecuteReturnIdentity();

                db.Deleteable<Entitys.article>(x => x.id == articleId).AS(table).ExecuteCommand();

                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                return false;
            }
            return true;
		}

		/// <summary>
		/// 得到一个对象实体
		/// </summary>
        public Entitys.article GetModel(string channelName, int article_id)
        {
            int channel_id = db.Queryable<Entitys.dt_site_channel>().Where(x => x.name == channelName).First().id;

            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;

            List<Entitys.dt_article_attribute_field> fields = db.Queryable<Entitys.dt_article_attribute_field, Entitys.dt_site_channel_field>((a, s) => new JoinQueryInfos(
                 JoinType.Inner, a.id == s.field_id
             )).Where((a, s) => s.channel_id == channel_id).OrderBy((a, s) => a.is_sys, OrderByType.Desc).OrderBy((a, s) => a.sort_id, OrderByType.Asc).OrderBy((a, s) => a.id, OrderByType.Desc).ToList();

            dynamic dynamicModel = db.Queryable<dynamic>().AS(table).Where(db.DbMaintenance.GetPrimaries(table)[0] + "=@id", new { id = article_id }).First();
            
            Entitys.article model = new Entitys.article();
            model.fields = new Dictionary<string, object>();

            PropertyInfo[] properties = model.GetType().GetProperties();
            foreach (KeyValuePair<string, object> kvp in dynamicModel)
            {
                if (properties.Any(x => x.Name == kvp.Key))
                {
                    PropertyInfo p = model.GetType().GetProperty(kvp.Key);
                    p.SetValue(model, kvp.Value);
                }
                else
                {
                    model.fields[kvp.Key] = kvp.Value;
                }
            }
            //Dictionary<string, object> fieldDic = new Dictionary<string, object>();
            //if (fields != null)
            //{
            //    if (fields.Count > 0)
            //    {
            //        foreach (Entitys.dt_article_attribute_field f in fields)
            //        {
            //            fieldDic.Add(f.name, dynamicModel.GetType().GetProperty(f.name).GetValue(dynamicModel));
            //        }
            //    }
            //}

            

            //Entitys.article model = db.Queryable<Entitys.article>().AS(table).Where(x => x.id == article_id).First();

            model.albums = new List<Entitys.dt_article_albums>();
            model.albums.AddRange(db.Queryable<Entitys.dt_article_albums>().Where(x => x.channel_id == channel_id && x.article_id == article_id).OrderBy(x => x.sort_id, OrderByType.Asc).ToList());

            model.attach = new List<Entitys.dt_article_attach>();
            model.attach.AddRange(db.Queryable<Entitys.dt_article_attach>().Where(x => x.channel_id == channel_id && x.article_id == article_id).OrderBy(x => x.sort_id, OrderByType.Asc).ToList());

            model.goods = new List<Entitys.dt_article_goods>();
            model.goods.AddRange(db.Queryable<Entitys.dt_article_goods>().Where(x => x.channel_id == channel_id && x.article_id == article_id).ToList());

            model.specs = new List<Entitys.dt_article_goods_spec>();
            model.specs.AddRange(db.Queryable<Entitys.dt_article_goods_spec>().Where(x => x.channel_id == channel_id && x.article_id == article_id).ToList());


            return model;

        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Entitys.article GetModel(string channelName, string call_index)
        {
            return null;
        }

		/// <summary>
		/// 获得前几行数据
		/// </summary>
        public List<Entitys.article> GetList(string channelName, int top, Expression<Func<Entitys.article, bool>> whereExpression, string filedOrder)
        {
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            return db.Queryable<Entitys.article>().AS(table).Take(top).Where(whereExpression).OrderBy(filedOrder).ToList();
        }
        public List<Entitys.article> GetFullList(string channelName, int top, Expression<Func<Entitys.article, bool>> whereExpression, string filedOrder)
        {
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            List<Entitys.article> list = new List<Entitys.article>();

            List<Entitys.article> tmpList = db.Queryable<Entitys.article>().AS(table).Take(top).Where(whereExpression).OrderBy(filedOrder).ToList();

            foreach (Entitys.article art in tmpList)
            {
                list.Add(GetModel(channelName, art.id));
            }
            return list;
        }

        public List<Entitys.article> GetList(string channelName, int top, string strWhere, string filedOrder)
        {
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            return db.Queryable<Entitys.article>().AS(table).Take(top).Where(strWhere).OrderBy(filedOrder).ToList();
        }
        public List<Entitys.article> GetFullList(string channelName, int top, string strWhere, string filedOrder)
        {
            List<Entitys.article> list = new List<Entitys.article>();
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            
            List<Entitys.article> tmpList = db.Queryable<Entitys.article>().AS(table).Take(top).Where(strWhere).OrderBy(filedOrder).ToList();

            foreach (Entitys.article art in tmpList)
            {
                list.Add(GetModel(channelName, art.id));
            }
            return list;
        }

        /// <summary>
        /// 获得查询分页数据
        /// </summary>
        public List<Entitys.article> GetList(string channelName, int categoryId, int pageSize, int pageIndex, Expression<Func<Entitys.article, bool>> whereExpression, string filedOrder, out int recordCount)
        {
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            recordCount = 0;
            Expression<Func<Entitys.article, bool>> expression = t => true;

            List<Entitys.dt_article_category> categories = db.Queryable<Entitys.dt_article_category>().Where(x => x.class_list.Contains("," + categoryId.ToString() + ",")).ToList();
            int[] arrayCategories = new int[categories.Count];
            for (int i = 0; i < categories.Count; i++)
            {
                arrayCategories[i] = categories[i].id;
            }
            if (categoryId > 0)
            {
                expression = expression.And(x => arrayCategories.Contains(x.category_id));
            }

            return db.Queryable<Entitys.article>().AS(table).Where(expression).Where(whereExpression).OrderBy(filedOrder).ToPageList(pageIndex, pageSize, ref recordCount);
        }



        public List<Entitys.article> GetFullList(string channelName, int categoryId, int pageSize, int pageIndex, Expression<Func<Entitys.article, bool>> whereExpression, string filedOrder, out int recordCount)
        {
            List<Entitys.article> list = new List<Entitys.article>();
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            recordCount = 0;
            Expression<Func<Entitys.article, bool>> expression = t => true;

            List<Entitys.dt_article_category> categories = db.Queryable<Entitys.dt_article_category>().Where(x => x.class_list.Contains("," + categoryId.ToString() + ",")).ToList();
            int[] arrayCategories = new int[categories.Count];
            for (int i = 0; i < categories.Count; i++)
            {
                arrayCategories[i] = categories[i].id;
            }
            if (categoryId > 0)
            {
                expression = expression.And(x => arrayCategories.Contains(x.category_id));
            }

            List<Entitys.article> tmpList = db.Queryable<Entitys.article>().AS(table).Where(expression).Where(whereExpression).OrderBy(filedOrder).ToPageList(pageIndex, pageSize, ref recordCount);

            foreach (Entitys.article art in tmpList)
            {
                list.Add(GetModel(channelName, art.id));
            }
            return list;
        }

        public List<Entitys.article> GetList(string channelName, int categoryId, int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount)
        {
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            recordCount = 0;
            Expression<Func<Entitys.article, bool>> expression = t => true;

            List<Entitys.dt_article_category> categories = db.Queryable<Entitys.dt_article_category>().Where(x => x.class_list.Contains("," + categoryId.ToString() + ",")).ToList();
            int[] arrayCategories = new int[categories.Count];
            for (int i = 0; i < categories.Count; i++)
            {
                arrayCategories[i] = categories[i].id;
            }
            if (categoryId > 0)
            {
                expression = expression.And(x => arrayCategories.Contains(x.category_id));
            }

            return db.Queryable<Entitys.article>().AS(table).Where(expression).Where(strWhere).OrderBy(filedOrder).ToPageList(pageIndex, pageSize, ref recordCount);
        }


        public List<Entitys.article> GetFullList(string channelName, int categoryId, int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount)
        {
            List<Entitys.article> list = new List<Entitys.article>();
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            recordCount = 0;
            Expression<Func<Entitys.article, bool>> expression = t => true;
            

            List<Entitys.dt_article_category> categories = db.Queryable<Entitys.dt_article_category>().Where(x => x.class_list.Contains("," + categoryId.ToString() + ",")).ToList();
            int[] arrayCategories = new int[categories.Count];
            for (int i = 0; i < categories.Count; i++)
            {
                arrayCategories[i] = categories[i].id;
            }
            if (categoryId > 0)
            {
                expression = expression.And(x => arrayCategories.Contains(x.category_id));
            }

            List<Entitys.article> tmpList = db.Queryable<Entitys.article>().AS(table).Where(expression).Where(strWhere).OrderBy(filedOrder).ToPageList(pageIndex, pageSize, ref recordCount);
            foreach (Entitys.article art in tmpList)
            {
                list.Add(GetModel(channelName, art.id));
            }
            return list;
        }

        #region 扩展方法================================
        /// <summary>
        /// 是否存在标题
        /// </summary>
        public bool ExistsTitle(string channelName, string title)
        {
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            return db.Queryable<Entitys.article>().AS(table).Where(x => x.title == title).Any();
        }

        /// <summary>
        /// 是否存在标题
        /// </summary>
        public bool ExistsTitle(string channelName, int categoryId, string title)
        {
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            return db.Queryable<Entitys.article>().AS(table).Where(x => x.title == title && x.category_id == categoryId).Any();
        }

        /// <summary>
        /// 返回信息标题
        /// </summary>
        public string GetTitle(string channelName, int article_id)
        {
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            Entitys.article model = db.Queryable<Entitys.article>().AS(table).Where(x => x.id == article_id).First();
            if (model == null)
                return "";
            else
                return model.title;
        }

        /// <summary>
        /// 返回信息内容
        /// </summary>
        public string GetContent(string channelName, int article_id)
        {
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            Entitys.article model = db.Queryable<Entitys.article>().AS(table).Where(x => x.id == article_id).First();
            if (model == null)
                return "";
            else
                return model.content;
        }

        /// <summary>
        /// 返回信息内容
        /// </summary>
        public string GetContent(string channelName, string call_index)
        {
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            Entitys.article model = db.Queryable<Entitys.article>().AS(table).Where(x => x.call_index == call_index).First();
            if (model == null)
                return "";
            else
                return model.content;
        }

        /// <summary>
        /// 返回信息封面图
        /// </summary>
        public string GetImgUrl(string channelName, int article_id)
        {
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            Entitys.article model = db.Queryable<Entitys.article>().AS(table).Where(x => x.id == article_id).First();
            if (model == null)
                return "";
            else
                return model.img_url;
        }

        /// <summary>
        /// 获取阅读次数
        /// </summary>
        public int GetClick(string channelName, int article_id)
        {
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            Entitys.article model = db.Queryable<Entitys.article>().AS(table).Where(x => x.id == article_id).First();
            if (model == null)
                return 0;
            else
                return model.click;
        }

        /// <summary>
        /// 返回数据总数
        /// </summary>
        public int GetCount(string channelName, Expression<Func<Entitys.article, bool>> expression)
        {
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            return db.Queryable<Entitys.article>().AS(table).Where(expression).Count();
        }

        /// <summary>
        /// 返回商品库存数量
        /// </summary>
        public int GetStockQuantity(string channelName, int channel_id, int article_id, int goods_id)
        {
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            if (goods_id > 0)
            {
                return Utils.ObjToInt(db.Queryable<Entitys.dt_article_goods>().Where(x => x.channel_id == channel_id && x.article_id == article_id && x.id == goods_id).First().stock_quantity);
            }
            else
            {
                return Utils.ObjToInt(GetModel(channelName, article_id).fields["stock_quantity"]);
            }
        }

        /// <summary>
        /// 修改一列数据
        /// </summary>
        public bool UpdateField(string channelName, Expression<Func<Entitys.article, Entitys.article>> expression, Expression<Func<Entitys.article, bool>> whereExpression)
        {
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            return db.Updateable<Entitys.article>().AS(table).SetColumns(expression).Where(whereExpression).ExecuteCommand() > 0;
        }
        public bool UpdateField(string channelName, Expression<Func<Entitys.article, bool>> expression, Expression<Func<Entitys.article, bool>> whereExpression)
        {
            string table = databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName;
            return db.Updateable<Entitys.article>().AS(table).SetColumns(expression).Where(whereExpression).ExecuteCommand() > 0;
        }


        #endregion

        //#region 前台模板调用方法========================
        ///// <summary>
        ///// 根据频道名称获取总记录数
        ///// </summary>
        //public int ArticleCount(string channelName, int categoryId, string strWhere)
        //{
        //    StringBuilder strSql = new StringBuilder();
        //    strSql.Append("select count(1) FROM " + databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName);
        //    strSql.Append(" where datediff(d,add_time,getdate())>=0");
        //    if (categoryId > 0)
        //    {
        //        strSql.Append(" and categoryId in(select id from " + databaseprefix + "article_category where class_list like '%," + categoryId + ",%')");
        //    }
        //    if (strWhere.Trim() != "")
        //    {
        //        strSql.Append(" and " + strWhere);
        //    }
        //    return Convert.ToInt32(DbHelperSQL.GetSingle(strSql.ToString()));
        //}

        ///// <summary>
        ///// 根据频道名称显示前几条数据
        ///// </summary>
        //public DataSet ArticleList(string channelName, int Top, string strWhere, string filedOrder)
        //{
        //    StringBuilder strSql = new StringBuilder();
        //    strSql.Append("select ");
        //    if (Top > 0)
        //    {
        //        strSql.Append(" top " + Top.ToString());
        //    }
        //    strSql.Append(" * FROM " + databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName);
        //    strSql.Append(" where datediff(d,add_time,getdate())>=0");
        //    if (strWhere.Trim() != "")
        //    {
        //        strSql.Append(" and " + strWhere);
        //    }
        //    strSql.Append(" order by " + filedOrder);
        //    return DbHelperSQL.Query(strSql.ToString());
        //}

        ///// <summary>
        ///// 根据频道名称显示前几条数据
        ///// </summary>
        //public DataSet ArticleList(string channelName, int categoryId, int Top, string strWhere, string filedOrder)
        //{
        //    StringBuilder strSql = new StringBuilder();
        //    strSql.Append("select ");
        //    if (Top > 0)
        //    {
        //        strSql.Append(" top " + Top.ToString());
        //    }
        //    strSql.Append(" * FROM " + databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName);
        //    strSql.Append(" where datediff(d,add_time,getdate())>=0");
        //    if (categoryId > 0)
        //    {
        //        strSql.Append(" and categoryId in(select id from " + databaseprefix + "article_category where class_list like '%," + categoryId + ",%')");
        //    }
        //    if (strWhere.Trim() != "")
        //    {
        //        strSql.Append(" and " + strWhere);
        //    }
        //    strSql.Append(" order by " + filedOrder);
        //    return DbHelperSQL.Query(strSql.ToString());
        //}

        ///// <summary>
        ///// 根据频道名称获得查询分页数据
        ///// </summary>
        //public DataSet ArticleList(string channelName, int categoryId, int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount)
        //{
        //    StringBuilder strSql = new StringBuilder();
        //    strSql.Append("select * FROM " + databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName);
        //    strSql.Append(" where datediff(d,add_time,getdate())>=0");
        //    if (categoryId > 0)
        //    {
        //        strSql.Append(" and categoryId in(select id from " + databaseprefix + "article_category where class_list like '%," + categoryId + ",%')");
        //    }
        //    if (strWhere.Trim() != "")
        //    {
        //        strSql.Append(" and " + strWhere);
        //    }
        //    recordCount = Convert.ToInt32(DbHelperSQL.GetSingle(PagingHelper.CreateCountingSql(strSql.ToString())));
        //    return DbHelperSQL.Query(PagingHelper.CreatePagingSql(recordCount, pageSize, pageIndex, strSql.ToString(), filedOrder));
        //}

        ///// <summary>
        ///// 根据频道名称及规格查询分页数据
        ///// </summary>
        //public DataSet ArticleList(string channelName, int categoryId, Dictionary<string, string> dicSpecIds, int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount)
        //{
        //    string specWhere = string.Empty;
        //    foreach (KeyValuePair<string, string> kv in dicSpecIds)
        //    {
        //        if (Utils.StrToInt(kv.Value, 0) > 0)
        //        {
        //            if (!string.IsNullOrEmpty(specWhere))
        //            {
        //                specWhere += "and ";
        //            }
        //            specWhere += "B.spec_ids like '%," + kv.Value + ",%'";
        //        }
        //    }
        //    if (!string.IsNullOrEmpty(specWhere))
        //    {
        //        specWhere = " and (" + specWhere + ")";
        //    }
        //    StringBuilder strSql = new StringBuilder();
        //    strSql.Append("select * FROM " + databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName);
        //    strSql.Append(" where datediff(d,add_time,getdate())>=0");
        //    if (categoryId > 0)
        //    {
        //        strSql.Append(" and categoryId in(select id from " + databaseprefix + "article_category where class_list like '%," + categoryId + ",%')");
        //    }
        //    if (strWhere.Trim() != "")
        //    {
        //        strSql.Append(" and " + strWhere);
        //    }
        //    if (!string.IsNullOrEmpty(specWhere))
        //    {
        //        strSql.Append(" and id in(");
        //        strSql.Append("select A.id from " + databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channelName + " as A," + databaseprefix + "article_goods as B");
        //        strSql.Append(" where A.channel_id=B.channel_id and A.id=B.article_id " + specWhere);
        //        strSql.Append(" group by A.id)");
        //    }
        //    recordCount = Convert.ToInt32(DbHelperSQL.GetSingle(PagingHelper.CreateCountingSql(strSql.ToString())));
        //    return DbHelperSQL.Query(PagingHelper.CreatePagingSql(recordCount, pageSize, pageIndex, strSql.ToString(), filedOrder));
        //}

        /// <summary>
        /// 获得关健字查询分页数据(搜索用到)
        /// </summary>
        public DataTable ArticleSearch(int site_id, int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount)
        {
            StringBuilder strSql = new StringBuilder();
            List<Entitys.dt_site_channel> channels = db.Queryable<Entitys.dt_site_channel>().Where(x => x.site_id == site_id).OrderBy(x => x.sort_id, OrderByType.Asc).OrderBy(x => x.id, OrderByType.Asc).ToList();
            if (channels != null)
            {
                if (channels.Count > 0)
                {
                    strSql.Append("select * from (");
                    for (int i = 0; i < channels.Count; i++)
                    {
                        strSql.Append("select id,site_id,channel_id,call_index,title,zhaiyao,add_time,img_url");
                        strSql.Append(" from " + databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channels[i].name);
                        strSql.Append(" where datediff(d,add_time,getdate())>=0");
                        if (strWhere.Trim() != "")
                        {
                            strSql.Append(" and " + strWhere);
                        }
                        if (i < (channels.Count - 1))
                        {
                            strSql.Append(" UNION ALL ");//合并频道数据表
                        }
                    }
                    strSql.Append(") as temp_article");
                }

                recordCount = Convert.ToInt32(db.Ado.GetScalar(PagingHelper.CreateCountingSql(strSql.ToString())));
                return db.Ado.GetDataTable(PagingHelper.CreatePagingSql(recordCount, pageSize, pageIndex, strSql.ToString(), filedOrder));
            }
            recordCount = 0;
            return new DataTable();
        }

        /// <summary>
        /// 获得Tags查询分页数据(搜索用到)
        /// </summary>
        public DataTable ArticleSearch(int site_id, string tags, int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount)
        {
            //查询站点频道列表
            List<Entitys.dt_site_channel> channels = db.Queryable<Entitys.dt_site_channel>().Where(x => x.site_id == site_id).OrderBy(x => x.sort_id, OrderByType.Asc).OrderBy(x => x.id, OrderByType.Asc).ToList();
            if (channels.Count > 0)
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append("select * from (");
                for (int i = 0; i < channels.Count; i++)
                {
                    strSql.Append("select id,site_id,A.channel_id,call_index,title,zhaiyao,add_time,img_url");
                    strSql.Append(" from " + databaseprefix + DTKeys.TABLE_CHANNEL_ARTICLE + channels[i].name + " as A INNER JOIN (");
                    strSql.Append("select R.channel_id,R.article_id");
                    strSql.Append(" from dt_article_tags_relation as R INNER JOIN dt_article_tags as S ON R.tag_id=S.id and S.title='" + tags + "'");
                    strSql.Append(") as T ON A.channel_id=T.channel_id and A.id=T.article_id");
                    strSql.Append(" where datediff(d,add_time,getdate())>=0");
                    if (strWhere.Trim() != "")
                    {
                        strSql.Append(" and " + strWhere);
                    }
                    if (i < (channels.Count - 1))
                    {
                        strSql.Append(" UNION ALL ");//合并频道数据表
                    }
                }
                strSql.Append(") as temp_article");
                recordCount = Convert.ToInt32(db.Ado.GetScalar(PagingHelper.CreateCountingSql(strSql.ToString())));
                return db.Ado.GetDataTable(PagingHelper.CreatePagingSql(recordCount, pageSize, pageIndex, strSql.ToString(), filedOrder));
            }
            recordCount = 0;
            return new DataTable();
        }
    }
}

